package com.zlyx.easy.core.utils;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 应用环境操作工具
 * </p>
 *
 * @author 赵光
 * @since 2020年5月26日
 */
@Component
public class EnvUtils implements EnvironmentAware {

	protected static Environment environment;

	@Override
	public void setEnvironment(Environment environment) {
		EnvUtils.environment = environment;
	}

	/**
	 * 读取配置
	 * 
	 * @param key
	 * @return
	 */
	public static String setProperty(String key, String value) {
		return System.setProperty(key, value);
	}

	/**
	 * 读取配置
	 * 
	 * @param key
	 * @return
	 */
	public static String getProperty(String key) {
		return getProperty(key, key);
	}

	/**
	 * 读取配置
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getProperty(String key, String defaultValue) {
		if (environment == null) {
			return defaultValue;
		}
		if (key.startsWith("${") && key.endsWith("}")) {
			key = key.substring(2, key.length() - 1);
			if (key.contains(":")) {
				return environment.getProperty(key.substring(0, key.indexOf(":")), key.substring(key.indexOf(":") + 1));
			}
		}
		String value = environment.getProperty(key);
		return StringUtils.isNotEmpty(value) ? value : defaultValue;
	}

	/**
	 * 读取配置
	 * 
	 * @return
	 */
	public static Environment getEnv() {
		return environment;
	}

}
